package org.zoomdev.zoom.dao.adapters.parameter;

import org.zoomdev.zoom.dao.adapters.ParameterAdapter;

import java.sql.Array;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Arrays;

// 基础类型数组适配器
public class PrimitiveArrayParameterAdapter<T> implements ParameterAdapter<T> {
    private final int jdbcType;
    private final String sqlTypeName;

    public PrimitiveArrayParameterAdapter(int jdbcType, String sqlTypeName) {
        this.jdbcType = jdbcType;
        this.sqlTypeName = sqlTypeName;
    }

    public int getSqlType() {
        return jdbcType;
    }

    @Override
    public void setNonnullParameter(PreparedStatement ps, int index, T data) throws SQLException {
        Connection conn = ps.getConnection();
        if (data instanceof int[]) {
            Array array = conn.createArrayOf(sqlTypeName, Arrays.stream((int[]) data).boxed().toArray());
            ps.setArray(index, array);
        } else if (data instanceof long[]) {
            Array array = conn.createArrayOf(sqlTypeName, Arrays.stream((long[]) data).boxed().toArray());
            ps.setArray(index, array);
        }
        // 处理其他基础类型数组...
        else if (data instanceof Object[]) {
            Array array = conn.createArrayOf(sqlTypeName, (Object[]) data);
            ps.setArray(index, array);
        } else {
            throw new SQLException("Unsupported array type: " + data.getClass());
        }
    }
}
